import { type ChangeEvent, type MouseEvent, useContext, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { createChildReply } from '@/services/api';
import useModal from '@/hooks/useModal';
import sanitizeHtml from 'sanitize-html';
import useToast, { LoginReminderContent } from 'hooks/useToast';
import { PostIdPageContext } from '@/contexts/post-id';
import Spinner from '@/app/[locale]/component/spinner/spinner';

export default function ChildReplyBtnPostIdH5Page({
  id,
  alias,
}: {
  id: number;
  alias: string;
}) {
  const context = useContext(PostIdPageContext);
  const { showModal, hideModal } = useModal();

  function onClickReply() {
    const modal = showModal({
      title: `@${alias}`,
      content: (
        <PostIdPageContext.Provider value={context}>
          <ReplyModal
            id={id}
            callback={() => {
              hideModal(modal);
            }}
          />
        </PostIdPageContext.Provider>
      ),
      isShowFooter: false,
    });
  }

  return (
    <div onClick={onClickReply} className="flex-shrink-0 py-2">
      <i className="bi bi-reply"></i>
    </div>
  );
}

const ReplyModal = ({
  id,
  callback,
}: {
  id: number;
  callback?: () => void;
}) => {
  const {
    source: { path },
    translatedFields,
    queryKey,
  } = useContext(PostIdPageContext)!;
  const [replyContent, setReplyContent] = useState('');
  const { show } = useToast();
  const queryClient = useQueryClient();

  const createReplyMutation = useMutation(createChildReply);

  async function onClickPostReply(e: MouseEvent<HTMLButtonElement>) {
    try {
      e.stopPropagation();
      e.preventDefault();

      if (!path.user) {
        show({
          type: 'PRIMARY',
          title: translatedFields.notLoggedInPrompt,
          content: <LoginReminderContent />,
        });
        return;
      }

      const _replyContent = replyContent.trim();
      if (!_replyContent) {
        setReplyContent('');
        show({
          type: 'DANGER',
          message: translatedFields.replyContentEmptyError,
        });
        return;
      }

      const content = sanitizeHtml(_replyContent);
      if (!content) {
        setReplyContent('');
        show({
          type: 'DANGER',
          message: translatedFields.replyContentEmptyError,
        });
        return;
      }

      await createReplyMutation.mutateAsync({
        data: {
          parentReplyId: id,
          content,
        },
      });

      if (queryKey.length > 0) {
        await queryClient.refetchQueries(queryKey, {}, { throwOnError: true });
      }

      setReplyContent('');
      show({
        type: 'SUCCESS',
        message: translatedFields.replyCompleted,
      });

      if (callback) {
        callback();
      }
    } catch (e) {
      createReplyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeCommentContent(e: ChangeEvent<HTMLTextAreaElement>) {
    setReplyContent(e.target.value);
  }

  return (
    <div className="row">
      <div className="col">
        <form className="vstack gap-4">
          <textarea
            name="replyContent"
            className="form-control"
            rows={5}
            placeholder={translatedFields.enterReply}
            value={replyContent}
            onChange={onChangeCommentContent}
          ></textarea>
          <button
            onClick={onClickPostReply}
            disabled={createReplyMutation.isLoading || !replyContent}
            type="button"
            className="btn btn-outline-primary"
          >
            {createReplyMutation.isLoading ? (
              <Spinner classs="me-2" />
            ) : (
              <i className="bi bi-cursor me-2"></i>
            )}
            {translatedFields.postReply}
          </button>
        </form>
      </div>
    </div>
  );
};
